import { useState, useEffect } from 'react';
import Modal from 'react-modal';
import './App.scss';

const DATA = {
  "data": {
    "grammar": [

    ],
    "mandatory": [

    ]
  },
  "errorCode": "string",
  "errorMessage": "string",
  "success": true
}

function Result({ grammar, mandatory }) {

  function preString(s) {
    return s.replace(/<grammar>/gi, '<i class="grammar">')
      .replace(/<\/grammar>/gi, '</i>')
      .replace(/<spelling>/gi, '<i class="spelling">')
      .replace(/<\/spelling>/gi, '</i>')
  }

  return (
    <div className="result">
      <h4 className="panel">PDF分析结果</h4>
      <div className="content">
        <div className="require">
          <h5><img className="ico" src="require.png" alt="" />必填项未填</h5>
          <ul>
            {
              mandatory.map((item, index) => (
                <li key={String(item)}><span>{index + 1}</span>{item}</li>
              ))
            }
          </ul>
        </div>
        <div className="error">
          <h5><img className="ico" src="error.png" alt="" />语法错误项</h5>
          <ul>
            {
              grammar.map((item, index) => (
                <li key={String(index)}>
                  <div dangerouslySetInnerHTML={{ __html: preString(item) }}></div>
                </li>
              ))
            }
          </ul>
        </div>
      </div>
    </div>
  )
}

function Info({ src = '', text = '', progress }) {
  const [len, setLen] = useState(0);
  useEffect(() => {
    if (progress && len < 95) {
      setTimeout(() => {
        setLen(len + 5)
      }, 200)
    }
  }, [progress, len])
  return (
    <div className="info-message">
      <img className="result-ico" src={src} alt="result" />
      {
        progress ? (
          <div className="bar">
            <div className="progress" style={{ width: len + '%' }}></div>
          </div>
        ) : null
      }
      <p className="text">{text}</p>
    </div>
  )
}

function App() {

  // 1.pendding 2.ing 3.success 4.error 5.network
  const [status, setStatus] = useState('pendding');
  const [templateOpen, setTemplateOpen] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');
  const [grammar, setGrammar] = useState([]);
  const [mandatory, setMandatory] = useState([]);
  useEffect(() => {
    getResult(DATA);
  }, []);

  function getResult(res) {
    if (res.success) {
      setGrammar(res.data.grammar);
      setMandatory(res.data.mandatory);
    } else {
      setStatus('error');
      setErrorMsg(res.errorMessage);
    }
  }

  function chooseFile(event) {
    setStatus('ing')
    let form = new FormData();
    form.append('file', event.target.files[0])
    fetch('http://47.88.13.166:8777/check', {
    // fetch('http://localhost:8777/check', {
      method: 'POST',
      body: form,
      // headers: {
      //   'Content-Type': 'multipart/form-data'
      // }
    })
      .then(data => {
        if (data.status !== 200) {
          setStatus('network')
          return null
        }
        return data.json()
      })
      .then(res => {
        setStatus("success");
        getResult(res);
      })
      .catch(error => {
        console.error(error)
      })
  }

  function triggerFile() {
    document.querySelector('#pdf').click()
  }

  return (
    <div className="app">
      <img className="logo" src="logo.png" alt="logo" />
      <img className="bg" src="bg.png" alt="bg" />
      <div className="info">请先选择要上传的PDF模版类型，再点击上传PDF文档</div>
      <div className="btns">
        <a onClick={() => setTemplateOpen(true)}>
          <img className="ico" src="doc.png" alt="" />
          选择PDF模板
        </a>
        <a onClick={() => triggerFile()}>
          <img className="ico" src="upload.png" alt="" />
          点击上传PDF
        </a>
        <input style={{ display: 'none' }} id="pdf" type="file" accept="application/pdf" onChange={(e) => chooseFile(e)} />
      </div>
      {status === 'pendding' ? (
        <Info src="result-success.png" text="请上传PDF格式文件" />
      ) : null}
      {status === 'ing' ? (
        <Info src="result-ing.png" progress text="PDF分析中..." />
      ) : null}
      {status === 'error' ? (
        <Info src="result-error.png" text={errorMsg} />
      ) : null}
      {status === 'network' ? (
        <Info src="result-network.png" text="网络中断，请检查网络连接并重新上传" />
      ) : null}
      {status === 'success' ? (
        <Result grammar={grammar} mandatory={mandatory} />
      ) : null}
      <Modal
        isOpen={templateOpen}
        style={{
          content: {
            top: '50%',
            left: '50%',
            right: 'auto',
            bottom: 'auto',
            marginRight: '-50%',
            transform: 'translate(-50%, -50%)',
            padding: 0,
            border: 'none',
            borderRadius: 5,
            background: '#FCCE80'
          },
          overlay: {
            background: 'rgba(44, 47, 60, 0.3)'
          }
        }}
      >
        <div className="template">
          <h5>选择PDF模板</h5>
          <ul>
            <li className="checked">Harvard</li>
          </ul>
          <div className="options">
            <a onClick={() => setTemplateOpen(false)}>取消</a>
            <a onClick={() => setTemplateOpen(false)} style={{ background: '#EB8E3D', color: '#FFFFFF' }}>确定</a>
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default App;
